//
//  ThirdViewController.m
//  XDCommonApp
//
//  Created by XD-XY on 2/12/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "ThirdViewController.h"
// 设置
#import "SettingsViewController.h"
#import "My_EditInfoViewController.h"

#import "loginViewController.h"

#import "UIImageView+WebCache.h"
#import "PersonCell.h"
// 优惠券
#import "YouHuiQuanViewController.h"
// 我的收藏
#import "FavirteViewController.h"
// 选择开通城市
#import "ChooseCityViewController.h"
// 常用地址
#import "CommonlyAddressViewController.h"


@interface ThirdViewController ()
{
    BOOL hasNew; //判断是否未查看优惠劵 yes表示有 no表示无
}
@end

@implementation ThirdViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if(ISLOGING){
        mTableView.tableHeaderView = isLoginHeadView;
        
        nameLB.text = [[NSUserDefaults standardUserDefaults] valueForKey:kMY_USER_NAME];
        [userIV sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] valueForKey:kMY_USER_FACE]] placeholderImage:[UIImage imageNamed:@"humanHeader"]];
        //判断新的优惠券
        [self getDataWithDict:@{@"CustomerID":[[NSUserDefaults standardUserDefaults] 				objectForKey:kMY_USER_ID] } api:API_GETYOUHUIQUAN];
        
        [XDTabBarViewController sharedXDTabBarViewController].reminder_IV2.hidden = YES;
    
    }else{
        mTableView.tableHeaderView = noLoginHeadView;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    [self.navigationBarView setHidden:YES];
    [self.contentView setHidden:YES];
    self.view.backgroundColor = UIColorFromRGB(0xf8f8f8);

// cell名字
    nameArray = [[NSArray alloc] initWithObjects:@"红包兑换",@"优惠券",@"我的收藏",@"选择开通城市", nil];
// cell图片
    iconImgArray = [[NSArray alloc] initWithObjects:(LOADIMAGE(@"mycentericon1@2x")),LOADIMAGE(@"mycentericon3@2x"),LOADIMAGE(@"mycentericon4@2x"),LOADIMAGE(@"mycentericon6@2x"),LOADIMAGE(@"mycentericon5@2x"), nil];


    [self initViews];
    
    self.leftBtn.hidden =YES;
    self.titleLabel.text = THIRDVIEWTITLETEXT;
}

#pragma mark
#pragma mark UI 布局
-(void)initViews
{
    mTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    mTableView.backgroundColor = [UIColor clearColor];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.showsVerticalScrollIndicator = NO;
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:mTableView];
    [self initHeadViews];
}

-(void)initHeadViews
{
    //登录成功的头部
    isLoginHeadView = [UIView initViewRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, 203) andBackGroudColor:mClearColor];

    UIImageView * bgIV = [UIImageView initImageViewRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, 183) andImage:LOADIMAGE(@"mycenterbg@2x") andUserInteractionEnabled:YES];
    [isLoginHeadView addSubview:bgIV];
    
    UIImageView * userbg = [UIImageView initImageViewRect:CGRectMake((320-76)/2.0f, 143/2.0f, 76, 76) andImage:LOADIMAGE(@"myh@2x") andUserInteractionEnabled:YES];
    userbg.backgroundColor = UIColorFromRGB(0xe5ccd3);
    userbg.layer.cornerRadius = 38;
    userbg.layer.masksToBounds = YES;
    [isLoginHeadView addSubview:userbg];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotopresonInfo)];
    [userbg addGestureRecognizer:tap];
    
    userIV = [UIImageView initImageViewRect:CGRectMake(2, 2, 72, 72) andImage:nil andUserInteractionEnabled:YES];
    userIV.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"placeholderHeader"]];
    userIV.layer.cornerRadius = 36;
    userIV.layer.masksToBounds = YES;
    userIV.layer.rasterizationScale = [UIScreen mainScreen].scale;
    userIV.layer.shouldRasterize   = YES;
    userIV.clipsToBounds = YES;
    userIV.contentMode = UIViewContentModeScaleAspectFill;//跟微信一样 填充
    [userbg addSubview:userIV];
    
    nameLB = [UILabel initLabelText:@"" andRect:CGRectMake(0,183-37, UI_SCREEN_WIDTH, 37) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:16.5] andTextColor:[UIColor whiteColor] andTextAlignment:NSTextAlignmentCenter];
    [isLoginHeadView addSubview:nameLB];
    

    //未登录的头部
    noLoginHeadView = [UIView initViewRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, 203) andBackGroudColor:mClearColor];
    UIImageView * bgIV2 = [UIImageView initImageViewRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, 183) andImage:LOADIMAGE(@"mycenterbg@2x") andUserInteractionEnabled:YES];
    [noLoginHeadView addSubview:bgIV2];
    
    UIButton * loginBtn = [UIButton initButton:CGRectMake((320-118)/2.0f, 143/2.0f+5,118,40) btnImage:LOADIMAGE(@"my_center_login@2x") btnTitle:nil];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [loginBtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
    [noLoginHeadView addSubview:loginBtn];
    
    CGFloat h = IOS7?20:0;
    UIButton * setbutton = [UIButton initButton:CGRectMake(UI_SCREEN_WIDTH-11-50, h, 50, 44) btnImage:LOADIMAGE(@"mycenterset@2x") btnTitle:nil];
    [setbutton addTarget:self action:@selector(setButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [isLoginHeadView addSubview:setbutton];
    
    UIButton * setbutton2 = [UIButton initButton:CGRectMake(UI_SCREEN_WIDTH-50, h, 50, 44) btnImage:LOADIMAGE(@"mycenterset@2x") btnTitle:nil];
    [setbutton2 addTarget:self action:@selector(setButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [noLoginHeadView addSubview:setbutton2];

}

#pragma mark
#pragma mark UITableView Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [nameArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellName = @"cell";
    PersonCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (cell == nil){
        cell = [[PersonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
    }
    cell.iconIV.image = [iconImgArray objectAtIndex:indexPath.row];
    cell.titleLB.text = [nameArray objectAtIndex:indexPath.row];
    
    if (indexPath.row ==[nameArray count]-1){
        cell.rightLB.hidden = NO;
        cell.arrowIV.hidden = YES;
        cell.downline.frame = CGRectMake(0,44.5, UI_SCREEN_WIDTH, 0.5);
        cell.rightLB.text = @"北京";
    }else{
        cell.rightLB.hidden = YES;
        cell.arrowIV.hidden = NO;
        cell.downline.frame = CGRectMake(43,44.5, UI_SCREEN_WIDTH-43, 0.5);
        cell.rightLB.text =nil;
    }
    
    if (indexPath.row == 1&&hasNew) {
        cell.hasNewIV.hidden = NO;
        cell.hasNewIV.backgroundColor = [UIColor redColor];
    }else{
        cell.hasNewIV.hidden = YES;
    }
    
    if (indexPath.row == 0){
        cell.upline.hidden = NO;
    }else{
        cell.upline.hidden = YES;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (!ISLOGING) {
        [self loginClick];
        return;
    }

    switch (indexPath.row) {
        case 0:
        {
            //红包兑换
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入兑换码" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.alertViewStyle = UIAlertViewStylePlainTextInput;
            UITextField * tf = [alert textFieldAtIndex:0];
            tf.keyboardType = UIKeyboardTypeNumberPad;
            [alert show];
        }
            break;

        case 1:
        {
            //优惠券
            YouHuiQuanViewController * youhuiquan = [[YouHuiQuanViewController alloc] init];
            [self.navigationController pushViewController:youhuiquan animated:YES];
        }
            break;

        case 2:
        {
            //我的收藏
            FavirteViewController *favVC = [[FavirteViewController alloc]init];
            [self.navigationController pushViewController:favVC animated:YES];
        }
            break;

//        case 3:
//        {
//            //常用地址
//            CommonlyAddressViewController *commonlyAddresss = [[CommonlyAddressViewController alloc] init];
//            [self.navigationController pushViewController:commonlyAddresss animated:YES];
//        }
//            break;

        case 3:
        {
            //选择开通城市
            ChooseCityViewController * city = [[ChooseCityViewController alloc] init];
            [self.navigationController pushViewController:city animated:YES];
        }
            break;

        default:
            break;
    }
}

#pragma mark - AlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (!buttonIndex) {
        return;
    }else{
        //请求红包兑换接口
        [self changeYouHuiQuan:[alertView textFieldAtIndex:0].text];
    }
}

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView{
    if ([alertView textFieldAtIndex:0].text.length) {
        return YES;
    }else
        return NO;
}


- (void)changeYouHuiQuan:(NSString *)code{
    if (![XDTools NetworkReachable]) {
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }
    
    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:@{@"VoucherID":code} API:API_CHANGEYOUHUIQUAN];
    [request setCompletionBlock:^{
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        
        if([[tempDic objectForKey:@"status"]intValue] == 1){
            
            [XDTools showTips:@"兑换成功" toView:self.view];
            
            hasNew = YES;
            [mTableView reloadData];
            
        }else{
            [XDTools showTips:tempDic[@"msg"] toView:self.view];
            
        }
        
    }];
    
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
    }];
    [request startAsynchronous];
}




#pragma mark
#pragma mark 去登录注册
-(void)loginClick
{
    loginViewController * loginVC = [[loginViewController alloc] init];
    [self.navigationController pushViewController:loginVC animated:YES];
}

#pragma mark
#pragma mark 去个人信息页
-(void)gotopresonInfo
{
    My_EditInfoViewController *editInfoVC = [[My_EditInfoViewController alloc] init];
    [self.navigationController pushViewController:editInfoVC  animated:YES];
}

#pragma mark
#pragma mark 去设置页
-(void)setButtonClick
{
    SettingsViewController * setting = [[SettingsViewController alloc] init];
    [self.navigationController pushViewController:setting animated:YES];
}

#pragma mark
#pragma mark  请求是否有优惠劵
-(void)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{
    if (![XDTools NetworkReachable]) {
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }
    
    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        
        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
        
        DDLOG(@"temdic = %@",tempDic);
        
        if([[tempDic objectForKey:@"status"]intValue] == 1){
            NSArray * arr = [tempDic objectForKey:@"data"];
            
            
            if (!ARRAY_IS_NOT_EMPTY(tempDic[@"data"])){
                hasNew = NO;
                return ;
            }

            
            NSString * preNum = [[NSUserDefaults standardUserDefaults]objectForKey:@"VoucherNum"];
            NSString * currentNum = [NSString stringWithFormat:@"%d",arr.count];
            if (![preNum isEqualToString:currentNum]) {
                hasNew = YES;
                
            }else{
                //没有新优惠券
                hasNew = NO;
                //隐藏tabBar标注
                XDTabBarViewController * tabBar = [XDTabBarViewController sharedXDTabBarViewController];
                tabBar.reminder_IV2.hidden = YES;
            }
            [mTableView reloadData];
        }else{
            [XDTools showTips:tempDic[@"msg"] toView:self.contentView];
        }
    }];
    
    [request setFailedBlock:^{
        
    }];
    
    [request startAsynchronous];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
